<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>SM3算法文件加密</title>
</head>

<body>
    <div style="text-align:center;">
        <form name="form1">
            <p>
                <br /> <br />
            <div>
            加密文件: <input type="file" id="sm3file" name="sm3file" value="" size="100" />
                <input type="button" value="加密" onClick="doFileSM3();" /><br /><br /><br /><br />
            </div>
            <div>
                文件大小: <input type="text" id="fileSize" value="" size="100" /><br /><br /><br />
            </div>
            <div>
                加密结果: <input type="text" id="sm3key" value="" size="100" /><br /><br /><br />
            </div>
            <div>
                计算时间: <input type="text" id="time" value="" size="100" /><br /><br /><br />
            </div>
            
            </p>
        </form>
    </div>

    <script src="js/sm3.js"></script>
    <script src="js/long.js"></script>
    <script>

        function doFileSM3() {
            const file = document.getElementById("sm3file").files[0];
            var reader = new FileReader();
            var step = 2 * 1024 * 1024;
            var total = file.size;
            var cuLoaded = 0;
            let sm3keycur = sm3New()
            document.getElementById("fileSize").value = (total/1024/1024)+"  M"
            console.info("文件大小：" + file.size / 1024 / 1024 + "  M");
            let time = new Date().getTime();
            //开始读取
            readBlob(0);
            //读取一段成功
            reader.onload = function (e) {
                //处理读取的结果
                showResult(reader.result);
                //处理读取的结果
                cuLoaded += e.loaded;
                //如果没有读完，继续
                if (cuLoaded < total) {
                    readBlob(cuLoaded);
                } else {
                    cuLoaded = total;
                    var sm3Hash = sm3keycur.finalize();//得到的数据是个byte数组
                    var sm3HashHex = encodeByteToString(sm3Hash, 0, sm3Hash.length);//编码成16进制可见字符
                    console.log(`Sm3计算完成：${file.name} 大小:${file.size} 用时：${(new Date().getTime() - time) / 1000} s`);
                    document.getElementById("sm3key").value = sm3HashHex
                    document.getElementById("time").value = ((new Date().getTime() - time) / 1000)+" s"
                }
                console.log(1);
            }


            //指定开始位置，分块读取文件
            function readBlob(start) {
                //指定开始位置和结束位置读取文件
                var blob = file.slice(start, start + step);
                reader.readAsArrayBuffer(blob);

            }

            function showResult(result) {
                var bytes = new Uint8Array(result);
                sm3keycur.update(bytes);
            }



        }
    </script>
</body>

</html>